package net.flydy.ywxcx.wxcloudrun.config;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import net.flydy.ywxcx.wxcloudrun.common.StatusEnum;
import net.flydy.ywxcx.wxcloudrun.service.impl.MerchantService;
import net.flydy.ywxcx.wxcloudrun.vo.BaseResponse;
import net.flydy.ywxcx.wxcloudrun.vo.MyToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class MerchantLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private MerchantService merchantService;

    private void responseJson(HttpServletResponse response, String jsonStr) throws Exception{
        //更改response的默认吗表为gbk
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(jsonStr);
        writer.flush();
    }

    private void respBadToken(HttpServletResponse response) throws Exception{
        BaseResponse baseResponse = new BaseResponse(StatusEnum.TOKEN_BAD);
        baseResponse.setReqNo("bad");
        baseResponse.setMessage("no login");
        responseJson(response, JSONUtil.toJsonPrettyStr(baseResponse));
        response.flushBuffer();
    }

    private void respBadToken(HttpServletResponse response, StatusEnum statusEnum) throws Exception{
        BaseResponse baseResponse = new BaseResponse(statusEnum);
        baseResponse.setReqNo("bad");
        baseResponse.setMessage("no login");
        responseJson(response, JSONUtil.toJsonPrettyStr(baseResponse));
        response.flushBuffer();
    }


    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
        try {
            String yourFlag = request.getHeader("yourFlag");
            if (StringUtils.isBlank(yourFlag)) {
                respBadToken(response);
                return false;
            }
            String[] str = StringUtils.split(yourFlag, "@");
            if (str != null && str.length > 1) {
                String tokenId = str[0];
                //校验token
                if (!merchantService.checkToken(tokenId, str[1])) {
                    respBadToken(response);
                    return false;
                }
                MyToken myToken = merchantService.getAupdateToken(tokenId);
                if (myToken == null) {
                    respBadToken(response);
                    return false;
                }
                //存储Token到上下文
                request.setAttribute("token", myToken);
            }

        } catch (Exception e) {
            log.error("", e);
            respBadToken(response, StatusEnum.FAIL);
            return false;
        }
        return true;
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("执行了拦截器的afterCompletion方法");
        request.removeAttribute("token");
    }
}
